#!/bin/bash

#
# Lists files opened by a sysbox process and it's descendants.
#
# Usage: lsof_sysbox <pid>
#
# E.g.,
#
#   lsof_sysbox $(pidof sysbox-mgr)
#   lsof_sysbox $(pidof sysbox-fs)
#

# Given a pid, returns a list consisting of the process itself and its descendants.
# Borrowed from: https://unix.stackexchange.com/questions/415307/how-to-use-lsof-to-list-all-files-open-by-the-parent-process-and-its-children
function descendants() {
  ps -Ao pid= -o ppid= | PID=$1 perl -lae '
    push @{$children{$F[1]}}, $F[0];
    sub tree {
      my @pids=($_[0]);
      push @pids, tree($_) for @{$children{$_[0]}};
      return @pids;
    }
    END{print for tree $ENV{PID}}'
}

function usage() {
	printf "\n"
	printf "Usage: lsof_sysbox <pid>\n"
	printf "\n"
	printf "E.g.,\n"
	printf '   lsof_sysbox $(pidof sysbox-mgr)\n'
	printf '   lsof_sysbox $(pidof sysbox-fs)\n'
	printf "\n"
	exit 1
}

TARGET_PID=$1

if [ -z "$TARGET_PID" ]; then
	usage
fi

if [ "$EUID" -ne 0 ]; then
	echo "Please run as root."
	exit 1
fi

lsof -p "$(descendants "$TARGET_PID" | paste -sd, -)"
